package why.demo.list.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 网关CORS跨域配置
 * 
 * 这是一个简洁、可靠的CORS解决方案，专门解决Spring Cloud Gateway的跨域问题
 * 
 * @author why
 * @date 2025/9/24
 */
@Slf4j
@Configuration
public class CorsConfiguration {

    /**
     * CORS跨域过滤器
     * 
     * 这个过滤器会拦截所有请求，为跨域请求添加必要的响应头
     * 
     * @return WebFilter
     */
    @Bean
    public WebFilter corsFilter() {
        return (ServerWebExchange ctx, WebFilterChain chain) -> {
            ServerHttpRequest request = ctx.getRequest();
            ServerHttpResponse response = ctx.getResponse();
            HttpHeaders headers = response.getHeaders();
            
            // 获取请求信息
            String origin = request.getHeaders().getOrigin();
            String method = request.getMethod().name();
            String path = request.getURI().getPath();
            
            log.info("处理请求: {} {} Origin: {}", method, path, origin);
            
            // 设置CORS响应头
            if (origin != null && !origin.isEmpty()) {
                headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
            } else {
                headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://localhost:8080");
            }
            
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE,OPTIONS,HEAD,PATCH");
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, 
                "Origin,Content-Type,Accept,Authorization,Cookie,X-Requested-With," +
                "Access-Control-Request-Method,Access-Control-Request-Headers," +
                "X-Token,X-User-Id,Cache-Control");
            headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, 
                "Content-Type,Content-Length,Authorization,X-Total-Count");
            headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600");
            
            // 处理预检请求
            if (CorsUtils.isPreFlightRequest(request)) {
                log.info("处理预检请求: {}", path);
                response.setStatusCode(HttpStatus.OK);
                return response.setComplete();
            }
            
            return chain.filter(ctx);
        };
    }
}
